When you start digging into WordPress partials, things really open up on the theme side. Being able to reuse templates is a nice feature and can help keep your code nice and tidy but if your templates are using WordPress’ template tags, you can easily find yourself in situations where you need the markup from a partial but not the data.
To work around this, I use generic views that depend only on an array of data points. This allows me to reuse the same view in multiple places on a site without having to worry if I’m inside a post loop or rendering a specific template, etc. This really opens up flexibility in the UI and also makes it possible to move UI components between projects quite easily.
Once set up, rendering your views is as simple as the following:
The templates themselves all initialise their expected variables at the top of the file and the markup below. You’ll see there are no WordPress template tags in here which removes the context-dependency. ‘Dumb’ templates are nice and versatile.
The View class (which I’ve provided further down) is simple to set up and it only needs to know where to look for templates.
Just so you understand the use-case, here is an example of the View class being used within a WordPress template to render a view.
The View class is a static class the is super simple to configure and just as easy to use as you’ve seen from the previous Gists. You are free to take, use, and modify this class however you need to.